package com.ding.custommanagersys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ding.custommanagersys.bo.CustomBo;
import com.ding.custommanagersys.entity.Area;
import com.ding.custommanagersys.entity.Custom;
import com.ding.custommanagersys.entity.Member;
import com.ding.custommanagersys.entity.User;
import com.ding.custommanagersys.mapper.CustomMapper;
import com.ding.custommanagersys.service.IAreaService;
import com.ding.custommanagersys.service.ICustomService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ding.custommanagersys.service.IMemberService;
import com.ding.custommanagersys.service.IUserService;
import com.ding.custommanagersys.vo.CustomUpdateVo;
import com.ding.custommanagersys.vo.CustomVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ding
 * @since 2023-04-18
 */
@Service
public class CustomServiceImpl extends ServiceImpl<CustomMapper, Custom> implements ICustomService {

    @Autowired
    private CustomMapper customMapper;

    @Autowired
    private IAreaService areaService;

    @Autowired
    @Lazy
    private IUserService userService;

    @Override
    public Page<CustomVo> getAllCustom(CustomBo bo) {
        Page<CustomVo> page = new Page<>(bo.getPageNo(),bo.getPageSize());
        List<CustomVo> allCustom = customMapper.getAllCustom(page,bo.getNumber(),bo.getName());
        allCustom.forEach(o -> o.setAddress(
                o.getProvince() + o.getCity() + o.getCounty() + o.getDetailed()));

        //过滤出非会员用户 将其排在会员后面
        List<CustomVo> noVipList = allCustom.stream().filter(o -> "0".equals(o.getLevel())).collect(Collectors.toList());
        //过滤出 会员用户 将其排在前面
        List<CustomVo> vipList = allCustom.stream().filter(o -> !"0".equals(o.getLevel())).collect(Collectors.toList());
        vipList.sort((Comparator.comparing(CustomVo::getLevel)));

        List<CustomVo> list = new ArrayList<>();
        list.addAll(vipList);
        list.addAll(noVipList);
        page.setRecords(list);

        return page;
    }

    //添加客户信息
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer addCustom(CustomVo customVo) {

        //赋值Custom对象
        Custom custom = new Custom();
        custom.settMemberId(customVo.getMemberId());
        custom.settName(customVo.getName());
        custom.settPhone(customVo.getPhone());

        //获取当前数据库中id值最大的值，然后+1作为最新的id主键
        String maxUid = customMapper.maxUid();
        if(maxUid == null){
            maxUid = "360000";
        }
        int id = Integer.parseInt(maxUid);
        custom.settNumber(String.valueOf(id+1));

        User user = new User();
        user.settUserId(String.valueOf(id+1));
        user.settUsername(customVo.getUsername());
        user.settPassword("123456");

        userService.addUser(user);

        //获取地区字段，当地区字段全部相同，则不用新建地区，直接引用该地区地址即可，否则就新建地区
        Area area = new Area();
        area.settProvince(customVo.getProvince());
        area.settCity(customVo.getCity());
        area.settCounty(customVo.getCounty());
        area.settDetailed(customVo.getDetailed());
        Area areaByDet = areaService.getAreaByDet(area);
        if(areaByDet != null){
            custom.settAreaId(areaByDet.gettId());
        }else{
            Integer areaMaxUid = areaService.getMaxUid();
            if(areaMaxUid == null){
                areaMaxUid = 1000;
            }
            areaMaxUid++;
            area.settId(areaMaxUid);
            custom.settAreaId(areaMaxUid);
            areaService.addArea(area);
        }
        return customMapper.insert(custom);    //放最后

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer addCustomByRegister(CustomVo customVo){
        //赋值Custom对象
        Custom custom = new Custom();
        //默认地址
        custom.settAreaId(1000);
        custom.settNumber(customVo.getNumber());
        custom.settMemberId(customVo.getMemberId());

        return customMapper.insert(custom);    //放最后
    }

    @Override
    public Custom getOneCustom(String id) {
        QueryWrapper<Custom> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("t_number",id);
        return getOne(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer updateCustom(CustomUpdateVo customUpdateVo) {

        //赋值Custom对象
        Custom custom = new Custom();
        custom.settNumber(customUpdateVo.gettNumber());
        custom.settMemberId(customUpdateVo.gettMemberId());
        custom.settName(customUpdateVo.gettName());
        custom.settPhone(customUpdateVo.gettPhone());

        //获取地区字段，当地区字段全部相同，则不用新建地区，直接引用该地区地址即可，否则就新建地区
        Area area = new Area();
        area.settProvince(customUpdateVo.getProvince());
        area.settCity(customUpdateVo.getCity());
        area.settCounty(customUpdateVo.getCounty());
        area.settDetailed(customUpdateVo.getDetailed());
        Area areaByDet = areaService.getAreaByDet(area);
        if(areaByDet != null){
            custom.settAreaId(areaByDet.gettId());
        }else{
            Integer areaMaxUid = areaService.getMaxUid();
            areaMaxUid++;
            area.settId(areaMaxUid);
            custom.settAreaId(areaMaxUid);
            areaService.addArea(area);
        }

        return customMapper.updateCustom(custom);    //放最后
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer deleteCustom(List<String> customIds) {
        List<Custom> customList = customMapper.listCustom(customIds);
        //获取地区id
        List<Integer> areaId = customList.stream().map(Custom::gettAreaId).collect(Collectors.toList());

        //删除用户
        userService.deleteByIds(customIds);
        //删除对应的地区
        areaService.deleteArea(areaId);
        return customMapper.deleteCustomByIds(customIds);
    }
}
